package org.cqust.backend.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.cqust.backend.common.ApiResult;
import org.cqust.backend.dto.response.data.ImageSummaryDTO;
import org.cqust.backend.entity.ImageData;
import org.cqust.backend.service.DataService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


// 一般性数据，不需要鉴权，可以匿名访问
@RestController
@RequestMapping("/api/generalData")
public class GeneralDataController {
    private final DataService dataService;

    /**
     * 构造函数，初始化GeneralDataController。
     *
     * @param dataService 数据服务实例
     */
    public GeneralDataController(DataService dataService) {
        this.dataService = dataService;
    }

    /**
     * 获取任务的XML数据。
     *
     * @param missionId 任务ID
     * @return 包含任务XML数据的ApiResult对象
     */
    @Operation(summary = "获取任务的XML数据")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取任务XML数据", content = @Content(mediaType = "application/json")),
            @ApiResponse(responseCode = "404", description = "任务未找到", content = @Content),
            @ApiResponse(responseCode = "500", description = "服务器内部错误", content = @Content)
    })
    @GetMapping("/getMission/{missionId}")
    public ApiResult<String> getMission(@PathVariable int missionId) {
        return ApiResult.success(dataService.getMissionXml(missionId));
    }

    /**
     * 获取图片数据。
     * <p>
     * 注意：为缩小数据量，采用纯二进制返回，因此正确响应时不会返回ApiResult。
     * 需要检查响应码是否为200来判断执行是否成功。
     *
     * @param imageId 图片ID
     * @return 包含图片数据的ResponseEntity对象
     */
    @Operation(summary = "获取图片数据")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取图片数据", content = @Content(mediaType = "image/jpeg")),
            @ApiResponse(responseCode = "400", description = "图片未找到", content = @Content(mediaType = "application/json",schema = @Schema(implementation = ApiResult.class))),
            @ApiResponse(responseCode = "500", description = "服务器内部错误", content = @Content)
    })
    @GetMapping("/getImage/{imageId}")
    public ResponseEntity<?> getImage(@PathVariable int imageId) {
        byte[] imageBytes = dataService.getImageBytes(imageId);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG); // 根据实际情况设置图片类型
        return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
    }
    // @PutMapping("/update")
    // public ApiResult<String> updateImageDescription(@RequestParam Long id, @RequestParam String description) {
    //     dataService.updateImageDescription(id, description);
    //     return ApiResult.success("更新成功");
    // }
    @GetMapping("/getAllImage")
    @PreAuthorize("hasAuthority('Teacher')")
    public ApiResult<List<ImageSummaryDTO>> getAllImage(){
        return ApiResult.success(dataService.getAllImage());
    }

    /**
     * 上传图片接口。
     *
     * @param file 上传的图片文件
     * @return 包含图片ID的ApiResult对象
     */
    @Operation(summary = "上传图片", description = "接收图片文件并返回图片ID")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "图片上传成功", content = @Content(mediaType = "application/json")),
            @ApiResponse(responseCode = "400", description = "文件为空或格式错误", content = @Content),
            @ApiResponse(responseCode = "500", description = "服务器内部错误", content = @Content)
    })
    @PostMapping("/upload")
    @PreAuthorize("isAuthenticated()")
    public ApiResult<Long> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return ApiResult.error("上传的文件不能为空");
        }

        // 调用服务层保存图片并获取生成的图片ID

        return ApiResult.success(dataService.saveImage(file));
    }
}